package com.spice.im;


import java.io.File;






import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;































import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;


























import cn.finalteam.galleryfinal.GalleryHelper;
import cn.finalteam.galleryfinal.PhotoCropActivity;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.toolsfinal.BitmapUtils;
import cn.finalteam.toolsfinal.DateUtils;
import cn.finalteam.toolsfinal.DeviceUtils;
import cn.finalteam.toolsfinal.Logger;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
//import com.allen.ui.profile.FormatTools;
//import com.example.android.bitmapfun.util.AsyncTask;
//import com.speed.im.utils.AsyncTask;
//import com.speed.im.utils.AsyncTask.Status;
import com.lxb.uploadwithprogress.http.HttpMultipartPost;
import com.speed.im.login.EncryptionUtil;
//import com.speed.im.RegisterStep.onNextActionListener;
import com.spice.im.RegisterStep.onNextActionListener;
import com.spice.im.friend.SearchIQ;
import com.spice.im.friend.SearchIQResponse;
import com.spice.im.friend.SearchIQResponseProvider;
import com.spice.im.group.MucCreateActivity;
import com.spice.im.register.IsRegisteredIQ;
import com.spice.im.register.IsRegisteredIQResponse;
import com.spice.im.register.IsRegisteredIQResponseProvider;
import com.spice.im.register.RegisterAllIQ;
import com.spice.im.register.RegisterAllIQResponse;
import com.spice.im.register.RegisterAllIQResponseProvider;
import com.spice.im.register.RegisterIQ;
import com.spice.im.register.RegisterIQResponse;
import com.spice.im.register.RegisterIQResponseProvider;
import com.spice.im.register.RegisterSuppleMentIQ;
import com.spice.im.register.RegisterSuppleMentIQResponse;
import com.spice.im.register.RegisterSuppleMentIQResponseProvider;
import com.spice.im.utils.AsyncTask;
import com.spice.im.utils.HeaderLayout;
import com.spice.im.utils.PhotoUtils;
import com.spice.im.utils.HeaderLayout.HeaderStyle;
import com.stb.isharemessage.BeemApplication;
import com.stb.isharemessage.BeemService;
import com.stb.isharemessage.service.XmppConnectionAdapter;
import com.stb.isharemessage.service.aidl.IXmppConnection;
import com.stb.isharemessage.service.aidl.IXmppFacade;
import com.stb.isharemessage.utils.FileUtils;
//import com.stb.isharemessage.utils.HeaderLayout;
//import com.stb.isharemessage.utils.PhotoUtils;
////import com.stb.isharemessage.utils.PhotoUtils;
//import com.stb.isharemessage.utils.HeaderLayout.HeaderStyle;






























import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
//import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
//import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class RegisterActivity extends BaseActivity implements OnClickListener,onNextActionListener{
//    /**
//     * 静态加载ReconnectionManager，重连才能正常工作*/
//    static{   
//	    try{  
//	       Class.forName("org.jivesoftware.smack.ReconnectionManager");  
//	    }catch(Exception e){  
//	        e.printStackTrace();  
//	    }  
//    }
	private HeaderLayout mHeaderLayout;
	private ViewFlipper mVfFlipper;
	private Button mBtnPrevious;
	private Button mBtnNext;
	
	private Button mBtnSkip;

	private BaseDialog mBackDialog;
	private RegisterStep mCurrentStep;
	private StepPhone mStepPhone;
	private StepVerify mStepVerify;
	public  String verification = "";
	private StepSetPassword mStepSetPassword;
	private StepBaseInfo mStepBaseInfo;
	private StepBirthday mStepBirthday;
	private StepPhoto mStepPhoto;
	
	public String username = "";
	public String password = "";
	public String avatorpath = "";
	public String uidStr = "";
//	public byte[] avatorbytes = null;
 	public Map<String, String> attributes = new HashMap<String, String>();

	private int mCurrentStepIndex = 1;
	
    public String uploadHost;
    public String picuploadHost;
    public String downloadPrefix;
    
    private final static float TARGET_HEAP_UTILIZATION = 0.75f;
    private final static int CWJ_HEAP_SIZE = 6* 1024* 1024 ;
    private static final Intent SERVICE_INTENT = new Intent();
	static {
		//pkg,cls
//		SERVICE_INTENT.setComponent(new ComponentName("com.test", "com.stb.isharemessage.BeemService"));
//		SERVICE_INTENT.setComponent(new ComponentName("com.stb.isharemessage", "com.stb.isharemessage.BeemService"));
		SERVICE_INTENT.setComponent(new ComponentName("com.spice.im", "com.stb.isharemessage.BeemService"));//自身应用pkg名称，非service所在pkg名称
	}
	private final ServiceConnection mServConn = new BeemServiceConnection();
    private boolean mBinded = false;
    private IXmppFacade mXmppFacade;
    private IXmppConnection mConnection;
    protected Context mContext;
    
    private int fromRegisterInit = 0;//0 1 doStraightRegister4Uid 成功后赋值1，主要为了防止doStraightRegister4Uid后用户直接点击返回
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		mContext = this;
		mSettings = PreferenceManager.getDefaultSharedPreferences(this);
		
        Properties props = new Properties();
        try {
            int id = this.getResources().getIdentifier("androidpn", "raw",
            		this.getPackageName());
            props.load(this.getResources().openRawResource(id));
        } catch (Exception e) {
//            Log.e(LOGTAG, "Could not find the properties file.", e);
            // e.printStackTrace();
        }
        uploadHost = props.getProperty("uploadHost", "");
        picuploadHost = props.getProperty("picuploadHost", "");
        downloadPrefix = props.getProperty("downloadPrefix", "");
		
		initViews();
		mCurrentStep = initStep();
		initEvents();
		initBackDialog();
		
		
		errorMsg2.put("0001","0001 已登陆，不能注册");
		errorMsg2.put("0002","0002 用户名非法（为空或这长度不是3-15位）");
		errorMsg2.put("0003","0003 用户名包含非法字符");
		errorMsg2.put("0004","0004 用户名已被注册");
		errorMsg2.put("0006","0006 未开放注册");
		errorMsg2.put("0007","0007 未开放邀请注册");
		errorMsg2.put("0008","0008 密码非法（为空或包含转意符）");
		errorMsg2.put("0008","0009 两次输入密码不一致");
		errorMsg2.put("0010","0010 email邮箱格式不对");
		errorMsg2.put("0011","0011 email邮箱已被注册");
		errorMsg2.put("0012","0012 同意个ip不允许一小时内同时注册多个用户");
		errorMsg2.put("9998","9998 注册失败");
		errorMsg2.put("0000","0000|newUid 注册成功，返回uid");
		errorMsg2.put("9999","9999 注册失败");
		errorMsg2.put("9997","9997 服务连接中1-1,请稍候再试.");
	}
	
	@Override
	protected void onResume(){
		super.onResume();
//    	try{
//			if (!mBinded){
//			    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);	    
//			}
//    	}catch(Exception e){
//    		e.printStackTrace();
//    	}
		if (!mBinded){
			Intent intent = new Intent(this, BeemService.class);
//			intent.putExtra("uFlag_startfromsetting", "1");
			mBinded = bindService(intent, mServConn, BIND_AUTO_CREATE);
		}
	}
    @Override
    protected void onPause() {
		super.onPause();
//		if (mBinded) {
//			unbindService(mServConn);
//			mBinded = false;
//		}
    }
    @Override
    protected void onStart() {
    	super.onStart();
        if (!mBinded)
    	    mBinded = bindService(RegisterActivity.SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);
//    	IntentFilter filter = new IntentFilter(MemorizingTrustManager.INTERCEPT_DECISION_INTENT
//    		+ "/" + getPackageName());
//    	filter.setPriority(RECEIVER_PRIORITY);
//    	registerReceiver(mSslReceiver, filter);
    }
    
//    @Override
//    protected void onStop() {
//		super.onStop();
//		if (mBinded) {
//		    unbindService(mServConn);
//		    mXmppFacade = null;
//		    mBinded = false;
//		}
////		unregisterReceiver(mSslReceiver);
//    }
	@Override
	protected void onDestroy() {
		PhotoUtils.deleteImageFile(this);
		mBackDialog.dismiss();
		super.onDestroy();
		if (mBinded) {
			unbindService(mServConn);
			mXmppFacade = null;
			mBinded = false;
		}
	}
	@Override
	protected void initViews() {
		mHeaderLayout = (HeaderLayout) findViewById(R.id.reg_header);
		mHeaderLayout.init(HeaderStyle.TITLE_RIGHT_TEXT);
		mVfFlipper = (ViewFlipper) findViewById(R.id.reg_vf_viewflipper);
		mVfFlipper.setDisplayedChild(0);
		mBtnPrevious = (Button) findViewById(R.id.reg_btn_previous);
		mBtnNext = (Button) findViewById(R.id.reg_btn_next);
		mBtnSkip = (Button) findViewById(R.id.reg_btn_skip);
	}

	@Override
	protected void initEvents() {
		mCurrentStep.setOnNextActionListener(this);
		mBtnPrevious.setOnClickListener(this);
		mBtnNext.setOnClickListener(this);
		mBtnSkip.setOnClickListener(this);
	}
	@Override
	public void onBackPressed() {
		if (mCurrentStepIndex <= 1) {
			if(mCurrentStepIndex == 1)
			mBackDialog.show();
		} else {
			doPrevious();
		}
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.reg_btn_previous:
			if (mCurrentStepIndex <= 1) {//<=1
				if(mCurrentStepIndex == 1)
				mBackDialog.show();
			} else {
				if(mCurrentStepIndex==4){//直接跳转登录
					Intent i = new Intent(RegisterActivity.this, Login.class);
				    i.putExtra("isConfig", 1);//0 false 1 true
				    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				    RegisterActivity.this.startActivity(i);
				    
				    RegisterActivity.this.finish();
				}else
				doPrevious();
			}
			break;

		case R.id.reg_btn_next:
			if (mCurrentStepIndex < 6) {
				if(mCurrentStepIndex==3){//设置完密码后直接注册，注册成功返回uid后再提示补全注册信息
					doNext();
					doStraightRegister4Uid();
				}else
				doNext();
			} else {
				if (mCurrentStep.validate()) {
					mCurrentStep.doNext();
				}
			}
			break;
		case R.id.reg_btn_skip:
			if(mCurrentStepIndex < 6 && mCurrentStepIndex==4){//跳过后续步骤直接注册账号密码
//				mBtnSkip.setVisibility(View.GONE);
				doStraightRegister();
			}else {
//				mBtnSkip.setVisibility(View.VISIBLE);
				mCurrentStep.doNext();
			}
		}
	}
    /*
	@SuppressWarnings("deprecation")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case PhotoUtils.INTENT_REQUEST_CODE_ALBUM:
			if (data == null) {
				return;
			}
			if (resultCode == RESULT_OK) {
				if (data.getData() == null) {
					return;
				}
				if (!FileUtils.isSdcardExist()) {
					showCustomToast("SD卡不可用,请检查");
					return;
				}
				Uri uri = data.getData();
				String[] proj = { MediaStore.Images.Media.DATA };
				Cursor cursor = managedQuery(uri, proj, null, null, null);
				if (cursor != null) {
					int column_index = cursor
							.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
					if (cursor.getCount() > 0 && cursor.moveToFirst()) {
						String path = cursor.getString(column_index);
						Bitmap bitmap = BitmapFactory.decodeFile(path);
						if (PhotoUtils.bitmapIsLarge(bitmap)) {
							PhotoUtils.cropPhoto(this, this, path);
						} else {
							mStepPhoto.setUserPhoto(bitmap);
							if(bitmap!=null){
								sendOfflineFile(path,"img");
//								iconpath = path;
								avatorpath = path;
//								avatorbytes = FormatTools.getInstance().Bitmap2Bytes(bitmap);
							}
						}
					}
				}
			}
			break;

		case PhotoUtils.INTENT_REQUEST_CODE_CAMERA:
			if (resultCode == RESULT_OK) {
				String path = mStepPhoto.getTakePicturePath();
				Bitmap bitmap = BitmapFactory.decodeFile(path);
				if (PhotoUtils.bitmapIsLarge(bitmap)) {
					PhotoUtils.cropPhoto(this, this, path);
				} else {
					mStepPhoto.setUserPhoto(bitmap);
					if(bitmap!=null){
						sendOfflineFile(path,"img");
//						iconpath = path;
						avatorpath = path;
//						avatorbytes = FormatTools.getInstance().Bitmap2Bytes(bitmap);
					}
				}
			}
			break;

		case PhotoUtils.INTENT_REQUEST_CODE_CROP:
			if (resultCode == RESULT_OK) {
				String path = data.getStringExtra("path");
				if (path != null) {
					Bitmap bitmap = BitmapFactory.decodeFile(path);
					if (bitmap != null) {
						mStepPhoto.setUserPhoto(bitmap);
						if(bitmap!=null){
							sendOfflineFile(path,"img");
//							iconpath = path;
							avatorpath = path;
//							avatorbytes = FormatTools.getInstance().Bitmap2Bytes(bitmap);
						}
					}
				}
			}
			break;
		}
	}
    */
	@Override
	public void next() {
		mCurrentStepIndex++;
		mCurrentStep = initStep();
		mCurrentStep.setOnNextActionListener(this);
		mVfFlipper.setInAnimation(this, R.anim.push_left_in);
		mVfFlipper.setOutAnimation(this, R.anim.push_left_out);
		mVfFlipper.showNext();
	}

	private RegisterStep initStep() {
		if(mCurrentStepIndex < 6 ){//&& mCurrentStepIndex!=4
			mBtnSkip.setVisibility(View.GONE);
		}else {
			mBtnSkip.setVisibility(View.VISIBLE);
		}
		
		switch (mCurrentStepIndex) {
		case 1:
			if (mStepPhone == null) {
				mStepPhone = new StepPhone(this, mVfFlipper.getChildAt(0));
			}
			mHeaderLayout.setTitleRightText("注册新账号", null, "1/6");
			mBtnPrevious.setText("返    回");
			mBtnNext.setText("下一步");
			return mStepPhone;

		case 2:
			if (mStepVerify == null) {
				mStepVerify = new StepVerify(this, mVfFlipper.getChildAt(1));
			}
			mHeaderLayout.setTitleRightText("填写验证码", null, "2/6");
			mBtnPrevious.setText("上一步");
			mBtnNext.setText("下一步");
			return mStepVerify;

		case 3:
			if (mStepSetPassword == null) {
				mStepSetPassword = new StepSetPassword(this,
						mVfFlipper.getChildAt(2));
			}
			mHeaderLayout.setTitleRightText("设置密码", null, "3/6");
			mBtnPrevious.setText("上一步");
			mBtnNext.setText("下一步");
			return mStepSetPassword;

		case 4:
			if (mStepBaseInfo == null) {
				mStepBaseInfo = new StepBaseInfo(this, mVfFlipper.getChildAt(3));
			}
			mHeaderLayout.setTitleRightText("填写基本资料", null, "4/6");
			mBtnPrevious.setText("以后再说");
//			mBtnSkip.setText("跳过直接注册");
			mBtnNext.setText("下一步");
			return mStepBaseInfo;

		case 5:
			if (mStepBirthday == null) {
				mStepBirthday = new StepBirthday(this, mVfFlipper.getChildAt(4));
			}
			mHeaderLayout.setTitleRightText("您的生日", null, "5/6");
			mBtnPrevious.setText("上一步");
			mBtnNext.setText("下一步");
			return mStepBirthday;

		case 6:
			if (mStepPhoto == null) {
				mStepPhoto = new StepPhoto(this, mVfFlipper.getChildAt(5));
			}
			mHeaderLayout.setTitleRightText("设置头像", null, "6/6");
			mBtnPrevious.setText("上一步");
			mBtnSkip.setText("跳过直接注册");
			mBtnNext.setText("注    册");
			return mStepPhoto;
		}
		return null;
	}

	private void doPrevious() {
		mCurrentStepIndex--;
		mCurrentStep = initStep();
		mCurrentStep.setOnNextActionListener(this);
		mVfFlipper.setInAnimation(this, R.anim.push_right_in);
		mVfFlipper.setOutAnimation(this, R.anim.push_right_out);
		mVfFlipper.showPrevious();
	}

	private void doNext() {
		if (mCurrentStep.validate()) {
			if (mCurrentStep.isChange()) {
				mCurrentStep.doNext();
			} else {
				next();
			}
		}
	}

	private void initBackDialog() {
		mBackDialog = BaseDialog.getDialog(RegisterActivity.this, "提示",
				"确认要放弃注册或暂时不补全信息么?", "确认", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						if(fromRegisterInit==1){//20200314 增加 说明账号注册成功了，但是未补全信息
							Intent i = new Intent(RegisterActivity.this, LoginanimActivity.class);//Login.class
						    i.putExtra("isConfig", 1);//0 false 1 true
						    i.putExtra("fromRegister", 1);
						    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						    startActivity(i);
						}
						finish();
					}
				}, "取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});
		mBackDialog.setButton1Background(R.drawable.btn_default_popsubmit);

	}
	@Override
	protected void putAsyncTask(AsyncTask<Void, Void, Boolean> asyncTask) {
		super.putAsyncTask(asyncTask);
	}

	@Override
	protected void showCustomToast(String text) {
		super.showCustomToast(text);
	}

	@Override
	protected void showLoadingDialog(String text) {
		super.showLoadingDialog(text);
	}

	@Override
	protected void dismissLoadingDialog() {
		super.dismissLoadingDialog();
	}

	protected int getScreenWidth() {
		return mScreenWidth;
	}
	protected String getPhoneNumber() {
		if (mStepPhone != null) {
			return mStepPhone.getPhoneNumber();
		}
		return "";
	}
	
	
	public SharedPreferences mSettings;
    private static final boolean DEFAULT_BOOLEAN_VALUE = false;
	private static final String DEFAULT_STRING_VALUE = "";
	private static final int DEFAULT_XMPP_PORT = 5222;
	public static final int NOTIFICATION_DURATION = Toast.LENGTH_SHORT;
    public int isRegister(String username) {
    	int int_isregister = 2;//0 未注册可以注册,1已注册,2注册状态未知（通讯错误）
	    try {
	    	mConnection = mXmppFacade.createConnection();
		    if (!mConnection.connect()) {
		    	Log.d("######@@@@@@******RegisterActivity result000******@@@@@@######", "result000");
		    	BeemApplication.getInstance().setConnected(false);
	    		int_isregister = 2;
		    }else{
		    	Log.d("######@@@@@@******RegisterActivity result111******@@@@@@######", "result111");
	    	if(mXmppFacade!=null){
	    		Log.d("######@@@@@@******RegisterActivity result333******@@@@@@######", "result333");
		    	if (mXmppFacade.getXmppConnectionAdapter()!=null 
						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null
						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected() 
						&& mXmppFacade.getXmppConnectionAdapter().login()//注意，第三方登陆login之前，需要调用框架本身的auth接口
//		    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated() //登录成功后才会startService，因此登录时不要判断isAuthenticated及isAlive
//		    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
		    			){
		    		Log.d("######@@@@@@******RegisterActivity result444******@@@@@@######", "result444");
		    		IsRegisteredIQ reqXML = new IsRegisteredIQ();
		            reqXML.setId("1234567890");
		            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
		            reqXML.setUsername(username);
		            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,username);
		            reqXML.setUuid(uuid);
//		            String hashcode = "";//apikey+uuid+username 使用登录成功后返回的sessionid作为密码做3des运算
		            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+uuid+username;
		            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
		            reqXML.setHashcode(hash_dest);
		            reqXML.setType(IQ.Type.SET);
		            String elementName = "isregisterediq"; 
		    		String namespace = "com:isharemessage:isregisterediq";
		    		IsRegisteredIQResponseProvider provider = new IsRegisteredIQResponseProvider();
		            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "isregisterediq", "com:isharemessage:isregisterediq", provider);
		            
		            if(rt!=null){
		                if (rt instanceof IsRegisteredIQResponse) {
		                	final IsRegisteredIQResponse isRegisteredIQResponse = (IsRegisteredIQResponse) rt;

		                    if (isRegisteredIQResponse.getChildElementXML().contains(
		                            "com:isharemessage:isregisterediq")) {
		    					RegisterActivity.this.runOnUiThread(new Runnable() {
			                    	
        							@Override
        							public void run() {
        								showCustomToast("服务器应答消息："+isRegisteredIQResponse.toXML().toString());
        							}
        						});
		                        String Id = isRegisteredIQResponse.getId();
		                        String Apikey = isRegisteredIQResponse.getApikey();
		                        String retcode = isRegisteredIQResponse.getRetcode();
		                        //0001 用户名不允许为空
		                        //0002 查询用户失败,hash校验失败
		                        //0003 用户名包含非法字符
		                        //0004 此用户名已被注册
		                        //0005 此用户名不允许注册
		                        //9997 查询用户失败
		                        String memo = isRegisteredIQResponse.getMemo();
		                        String isregister = isRegisteredIQResponse.getIsregister();//是否已注册 : 0 未注册 1 已注册额
		                        
		                        verification = isRegisteredIQResponse.getVerification();//验证码
		                        
		                        if(retcode.equals("0000")){
		                        	int_isregister = 0;
//		                        	verification
		                        }else if(retcode.equals("0001"))
		                        	int_isregister = 3;
		                        else if(retcode.equals("0002"))
		                        	int_isregister = 4;
		                        else if(retcode.equals("0003"))
		                        	int_isregister = 5;
		                        else if(retcode.equals("0004"))
		                        	int_isregister = 6;
		                        else if(retcode.equals("0005"))
		                        	int_isregister = 7;
		                        else if(retcode.equals("9997"))
		                        	int_isregister = 8;
		                        
		                        
		                    }else
		                    	int_isregister = 2;
		                } 
		            }else
		            	int_isregister = 2;
		    	}else{
		    		Log.d("######@@@@@@******RegisterActivity result555******@@@@@@######", "result555");
		    		BeemApplication.getInstance().setConnected(false);
		    		int_isregister = 2;
		    	}
	    	}else{
	    		Log.d("######@@@@@@******RegisterActivity result222******@@@@@@######", "result222");
	    		BeemApplication.getInstance().setConnected(false);
	    		int_isregister = 2;
	    	}
		    }
	    } catch (RemoteException e) {
	    	e.printStackTrace();
	    	BeemApplication.getInstance().setConnected(false);
	    	int_isregister = 2;
	    	
	    } catch (Exception e){
	    	e.printStackTrace();
	    	BeemApplication.getInstance().setConnected(false);
	    	int_isregister = 2;
	    }
    	return int_isregister;
    }
    
    public String errorMsg = null;
    
	public HashMap errorMsg2 = new HashMap();
//	String[]{"0001 已登陆，不能注册",
//				    		"0002 用户名非法（为空或这长度不是3-15位）",
//				    		"0003 用户名包含非法字符",
//				    		"0004 用户名已被注册",
//				    		"0006 未开放注册",
//				    		"0007 未开放邀请注册",
//				    		"0008 密码非法（为空或包含转意符）",
//				    		"0009 两次输入密码不一致",
//				    		"0010 email邮箱格式不对",
//				    		"0011 email邮箱已被注册",
//				    		"0012 同意个ip不允许一小时内同时注册多个用户",
//				    		"9998 注册失败",
//				    		"0000|newUid 注册成功，返回uid",
//				    		"9999 注册失败",
//				    		"9997 服务连接中1-1,请稍候再试."};
	public String errorType = "9999";
	
    /**
     * Create an account on the XMPP server specified in settings.
     * @param username the username of the account.
     * @param password the password of the account.
     * @return true if the account was created successfully.
     */
    public String createAccount(String username, String password,Map<String, String> attributes2) {
    	try{
	    	if(mXmppFacade!=null){
	    		Log.d("######@@@@@@******RegisterActivity result333******@@@@@@######", "result333");
		    	if (mXmppFacade.getXmppConnectionAdapter()!=null 
						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null
						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected() 
						&& mXmppFacade.getXmppConnectionAdapter().login()//注意，第三方登陆login之前，需要调用框架本身的auth接口
	//	    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated() //登录成功后才会startService，因此登录时不要判断isAuthenticated及isAlive
	//	    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
		    			){
		    		Log.d("######@@@@@@******RegisterActivity result444******@@@@@@######", "result444");
		    		RegisterIQ reqXML = new RegisterIQ();
		            reqXML.setId("1234567890");
		            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
//		            reqXML.setUid("--");
		            reqXML.setUsername(username);
		            reqXML.setPassword(password);
		            reqXML.setPassword2(password);
		            reqXML.setEmail(attributes2.get("email"));
		            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,username);
		            reqXML.setUuid(uuid);
		            
	//	            String hashcode = "";//apikey+uuid+username 使用登录成功后返回的sessionid作为密码做3des运算
		            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+uuid;
		            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
		            reqXML.setHashcode(hash_dest);
		            reqXML.setType(IQ.Type.SET);
		            String elementName = "registeriq"; 
		    		String namespace = "com:isharemessage:registeriq";
		    		RegisterIQResponseProvider provider = new RegisterIQResponseProvider();
		            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "registeriq", "com:isharemessage:registeriq", provider);
		            
		            if(rt!=null){
		                if (rt instanceof RegisterIQResponse) {
		                	final RegisterIQResponse registerIQResponse = (RegisterIQResponse) rt;
	
		                    if (registerIQResponse.getChildElementXML().contains(
		                            "com:isharemessage:registeriq")) {
		    					RegisterActivity.this.runOnUiThread(new Runnable() {
			                    	
	    							@Override
	    							public void run() {
	    								showCustomToast("服务器应答消息："+registerIQResponse.toXML().toString());
	    							}
	    						});
		                        String Id = registerIQResponse.getId();
		                        String Apikey = registerIQResponse.getApikey();
		                        String retcode = registerIQResponse.getRetcode();
		                        //0001 已登陆，不能注册
					    		//0002 用户名非法（为空或这长度不是3-15位）
					    		//0003 用户名包含非法字符
					    		//0004 用户名已被注册
					    		//0006 未开放注册
					    		//0007 未开放邀请注册
					    		//0008 密码非法（为空或包含转意符）
					    		//0009 两次输入密码不一致
					    		//0010 email邮箱格式不对
					    		//0011 email邮箱已被注册
					    		//0012 同意个ip不允许一小时内同时注册多个用户
					    		//9998 注册失败
					    		//0000|newUid 注册成功，返回uid
					    		//9999 注册失败
		                        String memo = registerIQResponse.getMemo();
		                        String uid = registerIQResponse.getUid();//是否已注册 : 0 未注册 1 已注册额
		                        attributes.put("uid", uid);
		                        uidStr = uid;
		                        if(retcode.startsWith("0000"))
		                        	errorType = "0000";
		                        else
		                        errorType = retcode;
		                        
		                        
		                    }else
		                    	errorType = "9997";
		                } 
		            }else
		            	errorType = "9997";
		    	}else{
		    		Log.d("######@@@@@@******RegisterActivity result555******@@@@@@######", "result555");
		    		BeemApplication.getInstance().setConnected(false);
		    		errorType = "9997";
		    	}
	    	}else{
	    		Log.d("######@@@@@@******RegisterActivity result222******@@@@@@######", "result222");
	    		BeemApplication.getInstance().setConnected(false);
	    		errorType = "9997";
	    	}
    	}catch(RemoteException e){
    		e.printStackTrace();
    		errorType = "9997";
    	}catch(Exception e){
    		e.printStackTrace();
    		errorType = "9997";
    	}
		return errorType;
    }
    
    
    /**
     * Create an account on the XMPP server specified in settings.
     * @param username the username of the account.
     * @param password the password of the account.
     * @return true if the account was created successfully.
     */
    public String createAccountAll(String username, String password,Map<String, String> attributes2) {
    	try{
	    	if(mXmppFacade!=null){
	    		Log.d("######@@@@@@******RegisterActivity result333******@@@@@@######", "result333");
		    	if (mXmppFacade.getXmppConnectionAdapter()!=null 
						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null
						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected() 
						&& mXmppFacade.getXmppConnectionAdapter().login()//注意，第三方登陆login之前，需要调用框架本身的auth接口
	//	    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated() //登录成功后才会startService，因此登录时不要判断isAuthenticated及isAlive
	//	    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
		    			){
		    		Log.d("######@@@@@@******RegisterActivity result444******@@@@@@######", "result444");
		    		RegisterAllIQ reqXML = new RegisterAllIQ();
		            reqXML.setId("1234567890");
		            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
//		            reqXML.setUid("--");
		            reqXML.setUsername(username);
		            reqXML.setPassword(password);
		            reqXML.setPassword2(password);
		            reqXML.setEmail(attributes2.get("email"));
		            reqXML.setName(attributes2.get("name"));
		            reqXML.setAvatar(attributes2.get("avatar"));
		            reqXML.setNote(attributes2.get("note"));
		            reqXML.setSex(attributes2.get("sex"));
		            reqXML.setBirthyear(attributes2.get("birthyear"));
		            reqXML.setBirthmonth(attributes2.get("birthmonth"));
		            reqXML.setBirthday(attributes2.get("birthday"));
		            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,username);
		            reqXML.setUuid(uuid);
		            
	//	            String hashcode = "";//apikey+uuid+username 使用登录成功后返回的sessionid作为密码做3des运算
		            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+uuid;
		            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
		            reqXML.setHashcode(hash_dest);
		            reqXML.setType(IQ.Type.SET);
		            String elementName = "registeralliq"; 
		    		String namespace = "com:isharemessage:registeralliq";
		    		RegisterAllIQResponseProvider provider = new RegisterAllIQResponseProvider();
		            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "registeralliq", "com:isharemessage:registeralliq", provider);
		            
		            if(rt!=null){
		                if (rt instanceof RegisterAllIQResponse) {
		                	final RegisterAllIQResponse registerAllIQResponse = (RegisterAllIQResponse) rt;
	
		                    if (registerAllIQResponse.getChildElementXML().contains(
		                            "com:isharemessage:registeralliq")) {
		    					RegisterActivity.this.runOnUiThread(new Runnable() {
			                    	
	    							@Override
	    							public void run() {
	    								showCustomToast("服务器应答消息："+registerAllIQResponse.toXML().toString());
	    							}
	    						});
		                        String Id = registerAllIQResponse.getId();
		                        String Apikey = registerAllIQResponse.getApikey();
		                        String retcode = registerAllIQResponse.getRetcode();
		                        //0001 已登陆，不能注册
					    		//0002 用户名非法（为空或这长度不是3-15位）
					    		//0003 用户名包含非法字符
					    		//0004 用户名已被注册
					    		//0006 未开放注册
					    		//0007 未开放邀请注册
					    		//0008 密码非法（为空或包含转意符）
					    		//0009 两次输入密码不一致
					    		//0010 email邮箱格式不对
					    		//0011 email邮箱已被注册
					    		//0012 同意个ip不允许一小时内同时注册多个用户
					    		//9998 注册失败
					    		//0000|newUid 注册成功，返回uid
					    		//9999 注册失败
		                        String memo = registerAllIQResponse.getMemo();
		                        String uid = registerAllIQResponse.getUid();//是否已注册 : 0 未注册 1 已注册额
		                        attributes.put("uid", uid);
		                        uidStr = uid;
		                        
		                        if(retcode.startsWith("0000"))
		                        	errorType = "0000";
		                        else
		                        errorType = retcode;
		                        
		                        
		                    }else
		                    	errorType = "9997";
		                } 
		            }else
		            	errorType = "9997";
		    	}else{
		    		Log.d("######@@@@@@******RegisterActivity result555******@@@@@@######", "result555");
		    		BeemApplication.getInstance().setConnected(false);
		    		errorType = "9997";
		    	}
	    	}else{
	    		Log.d("######@@@@@@******RegisterActivity result222******@@@@@@######", "result222");
	    		BeemApplication.getInstance().setConnected(false);
	    		errorType = "9997";
	    	}
    	}catch(RemoteException e){
    		e.printStackTrace();
    		errorType = "9997";
    	}catch(Exception e){
    		e.printStackTrace();
    		errorType = "9997";
    	}
		return errorType;
    }
    
    /**
     * Create an account on the XMPP server specified in settings.
     * @param username the username of the account.
     * @param password the password of the account.
     * @return true if the account was created successfully.
     */
    public String createAccountSuppleMent(Map<String, String> attributes2) {
    	try{
	    	if(mXmppFacade!=null){
	    		Log.d("######@@@@@@******RegisterActivity result333******@@@@@@######", "result333");
		    	if (mXmppFacade.getXmppConnectionAdapter()!=null 
						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null
						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected() 
						&& mXmppFacade.getXmppConnectionAdapter().login()//注意，第三方登陆login之前，需要调用框架本身的auth接口
	//	    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated() //登录成功后才会startService，因此登录时不要判断isAuthenticated及isAlive
	//	    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
		    			){
		    		Log.d("######@@@@@@******RegisterActivity result444******@@@@@@######", "result444");
		    		RegisterSuppleMentIQ reqXML = new RegisterSuppleMentIQ();
		            reqXML.setId("1234567890");
		            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
		            reqXML.setUid(attributes2.get("uid"));
		            reqXML.setName(attributes2.get("name"));
		            reqXML.setPhoto("");
//		            reqXML.setPhoto(attributes2.get("photo"));//用来更新sys_user表中的photo字段 20200314 备用
		            reqXML.setAvatar(attributes2.get("avatar"));
		            reqXML.setNote(attributes2.get("note"));
		            reqXML.setSex(attributes2.get("sex"));
		            if(attributes2.get("birthyear")!=null
		            		&& !attributes2.get("birthyear").equalsIgnoreCase("null")
		            		&& attributes2.get("birthyear").length()!=0){
			            reqXML.setBirthyear(attributes2.get("birthyear"));
			            reqXML.setBirthmonth(attributes2.get("birthmonth"));
			            reqXML.setBirthday(attributes2.get("birthday"));
		            }else{
		            	reqXML.setBirthyear(attributes2.get("1990"));
			            reqXML.setBirthmonth(attributes2.get("1"));
			            reqXML.setBirthday(attributes2.get("1"));
		            }
		            
//		            attributes2.get("photo");//用来更新sys_user表中的photo字段 20200314 备用
		            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
				    String login = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
		            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,login);
		            reqXML.setUuid(uuid);
		            
	//	            String hashcode = "";//apikey+uuid+username 使用登录成功后返回的sessionid作为密码做3des运算
		            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+attributes2.get("uid")+uuid;
		            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
		            reqXML.setHashcode(hash_dest);
		            reqXML.setType(IQ.Type.SET);
		            String elementName = "registersupplementiq"; 
		    		String namespace = "com:isharemessage:registersupplementiq";
		    		RegisterSuppleMentIQResponseProvider provider = new RegisterSuppleMentIQResponseProvider();
		            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "registersupplementiq", "com:isharemessage:registersupplementiq", provider);
		            
		            if(rt!=null){
		                if (rt instanceof RegisterSuppleMentIQResponse) {
		                	final RegisterSuppleMentIQResponse registerSuppleMentIQResponse = (RegisterSuppleMentIQResponse) rt;
	
		                    if (registerSuppleMentIQResponse.getChildElementXML().contains(
		                            "com:isharemessage:registersupplementiq")) {
		    					RegisterActivity.this.runOnUiThread(new Runnable() {
			                    	
	    							@Override
	    							public void run() {
	    								showCustomToast("服务器应答消息："+registerSuppleMentIQResponse.toXML().toString());
	    							}
	    						});
		                        String Id = registerSuppleMentIQResponse.getId();
		                        String Apikey = registerSuppleMentIQResponse.getApikey();
		                        String retcode = registerSuppleMentIQResponse.getRetcode();
		                        
					    		//0002 补全用户注册信息失败,hash校验失败
					    		//9999 补全用户注册信息失败
		                        //9997 补全用户注册信息失败
		                        //0000 补全用户注册信息成功
		                        String memo = registerSuppleMentIQResponse.getMemo();
		                        
		                        if(retcode.startsWith("0000"))
		                        	errorType = "0000";
		                        else
		                        errorType = retcode;
		                        
		                        
		                    }else
		                    	errorType = "9997";
		                } 
		            }else
		            	errorType = "9997";
		    	}else{
		    		Log.d("######@@@@@@******RegisterActivity result555******@@@@@@######", "result555");
		    		BeemApplication.getInstance().setConnected(false);
		    		errorType = "9997";
		    	}
	    	}else{
	    		Log.d("######@@@@@@******RegisterActivity result222******@@@@@@######", "result222");
	    		BeemApplication.getInstance().setConnected(false);
	    		errorType = "9997";
	    	}
    	}catch(RemoteException e){
    		e.printStackTrace();
    		errorType = "9997";
    	}catch(Exception e){
    		e.printStackTrace();
    		errorType = "9997";
    	}
		return errorType;
    }
    /**
     * Retrieve proxy use from the preferences.
     * @return Registered proxy use
     */
    private boolean getRegisteredProxyUse() {
    	return mSettings.getBoolean(BeemApplication.PROXY_USE_KEY, DEFAULT_BOOLEAN_VALUE);
    }
    /**
     * Retrieve proxy username from the preferences.
     * @return Registered proxy username
     */
    private String getRegisteredProxyUsername() {
    	return mSettings.getString(BeemApplication.PROXY_USERNAME_KEY, DEFAULT_STRING_VALUE);
    }
    /**
     * Retrieve proxy password from the preferences.
     * @return Registered proxy password
     */
    private String getRegisteredProxyPassword() {
    	return mSettings.getString(BeemApplication.PROXY_PASSWORD_KEY, DEFAULT_STRING_VALUE);
    }
    /**
     * Retrieve proxy port from the preferences.
     * @return Registered proxy port
     */
    private int getRegisteredProxyPort() {
    	return Integer.parseInt(mSettings.getString(BeemApplication.PROXY_PORT_KEY, DEFAULT_STRING_VALUE));
    }
    /**
     * Retrieve proxy server from the preferences.
     * @return Registered proxy server
     */
    private String getRegisteredProxyServer() {
    	return mSettings.getString(BeemApplication.PROXY_SERVER_KEY, DEFAULT_STRING_VALUE);
    }
    /**
     * Retrieve xmpp port from the preferences.
     * @return Registered xmpp port
     */
    private int getXMPPPort() {
		int port = DEFAULT_XMPP_PORT;
		if (mSettings.getBoolean("settings_key_specific_server", false))
		    port = Integer.parseInt(mSettings.getString("settings_key_xmpp_port", "5222"));
		return port;
    }

    /**
     * Retrieve xmpp server from the preferences.
     * @return Registered xmpp server
     */
    private String getXMPPServer() {
//		TextView xmppServerTextView = (TextView) findViewById(R.id.create_account_username);
		String xmppServer = "124.127.117.238";//10.0.2.2
		if (mSettings.getBoolean("settings_key_specific_server", false))
		    xmppServer = mSettings.getString("settings_key_xmpp_server", "124.127.117.238").trim();//10.0.2.2
		//注释掉:从用户名中的@resource中解析服务器地址
	//	else
	//	    xmppServer = StringUtils.parseServer(xmppServerTextView.getText().toString());
		return xmppServer;
    }
    /**
     * Retrieve TLS use from the preferences.
     * @return Registered TLS use
     */
    private boolean getRegisteredXMPPTLSUse() {
    	return mSettings.getBoolean("settings_key_xmpp_tls_use", DEFAULT_BOOLEAN_VALUE);
    }
    /**
     * Create a dialog containing an error message.
     * @param errMsg the error message
     */
    private void createErrorDialog(String errMsg) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.create_account_err_dialog_title)
		    .setMessage(errMsg)
		    .setCancelable(false)
		    .setIcon(android.R.drawable.ic_dialog_alert);
		builder.setNeutralButton(R.string.create_account_close_dialog_button, new DialogInterface.OnClickListener() {
	
		    @Override
		    public void onClick(DialogInterface dialog, int which) {
			dialog.cancel();
		    }
		});
		AlertDialog settingsErrDialog = builder.create();
		settingsErrDialog.show();
    }
    /*
    private HttpMultipartPost post;
    private static ExecutorService LIMITED_TASK_EXECUTOR;  
      
    static {    
        LIMITED_TASK_EXECUTOR = (ExecutorService) Executors.newFixedThreadPool(7);
    }; 
    private void sendOfflineFile(String filepath,String type) {
			try{
				post = new HttpMultipartPost(handler);
//				post.execute(filepath,xmppConnectionAdapter.getAdaptee().getUser(),mContact.getJIDWithRes());
//				Params[] params;
				handler.sendEmptyMessage(2);
				post.executeOnExecutor(LIMITED_TASK_EXECUTOR,
						filepath,
						username,
						username,
						type,
						"",
						picuploadHost);
//						"http://10.0.2.2:9090/plugins/picfiletransfer/picfiletransfer"); 
			}catch(Exception e){
				Log.e("error", "RejectedExecutionException in content_img: " +  filepath+";"+e.getMessage());
			}
		
	}
	private Handler handler = new Handler() {
		
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 2:
//				if(pb.getVisibility()==View.GONE){
//					pb.setMax(100);
//					pb.setProgress(0);
//					pb.setVisibility(View.VISIBLE);
//				}
				showLoadingDialog("请稍后,正在设置...0%");
				break;
			case 3:
//				pb.setProgress(msg.arg1);
				showLoadingDialog("请稍后,正在设置..."+msg.arg1*100/msg.arg2+"%");
				break;
			case 4:
//				pb.setVisibility(View.GONE);
//				upload = false;
				dismissLoadingDialog();
//				attributes.put("avatorpath", avatorpath);
				if(avatorpath!=null && avatorpath.length()!=0 && !avatorpath.equalsIgnoreCase("null"))
				attributes.put("email", avatorpath.substring(avatorpath.lastIndexOf(File.separator)+1));
				break;
			default:
				break;
			}
		}
	};
	*/
	
    /**
     * The service connection used to connect to the Beem service.
     */
    private class BeemServiceConnection implements ServiceConnection {
		/**
		 * Constructor.
		 */
		public BeemServiceConnection() {
		}
	
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
		    mXmppFacade = IXmppFacade.Stub.asInterface(service);
		    if(mXmppFacade!=null){
		    	mBinded = true;
		    }
		}
		@Override
		public void onServiceDisconnected(ComponentName name) {
		    mXmppFacade = null;
		    mBinded = false;
		}
    }
    
    
	public void doStraightRegister4Uid() {
		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				showLoadingDialog("请稍后,正在提交...");
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				try {
					Thread.sleep(2000);
//					return (mActivity.createAccount(mActivity.username, mActivity.password, mActivity.attributes));
					if((createAccount(username, password, attributes)).startsWith("0000"))
						return true;
//							&& mActivity.saveUserVCard(mActivity.avatorbytes, mActivity.username+"@pc2011040521xsg"));
//					return true;
				} catch (InterruptedException e) {

				}
				return false;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
				dismissLoadingDialog();
				if (result) {
				    Toast toast = Toast.makeText(RegisterActivity.this, String.format(
				    		getString(R.string.create_account_successfull_after), username), NOTIFICATION_DURATION);
				    	    toast.show();
				    	    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(RegisterActivity.this);
				    		SharedPreferences.Editor edit = settings.edit();
//				    		edit.putString(BeemApplication.ACCOUNT_USERNAME_KEY, mActivity.username+"@pc2011040521xsg");
				    		edit.putString(BeemApplication.ACCOUNT_USERNAME_KEY, username);
				    		edit.putString(BeemApplication.ACCOUNT_PASSWORD_KEY, password);
				    		edit.putString("uidStr", uidStr);
				    		edit.putString("uidStr"+username, uidStr);
				    		edit.commit();
				    		doNext();//成功后跳转到补全注册信息页面
				    		fromRegisterInit = 1;
				}else{
					Toast toast = Toast.makeText(RegisterActivity.this, (String)errorMsg2.get(errorType), NOTIFICATION_DURATION);
				    	    toast.show();
				    RegisterActivity.this.finish();
				}
			}

		});
	}
    
	public void doStraightRegister() {
		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				showLoadingDialog("请稍后,正在提交...");
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				try {
					Thread.sleep(2000);
//					return (mActivity.createAccount(mActivity.username, mActivity.password, mActivity.attributes));
					if((createAccount(username, password, attributes)).startsWith("0000"))
						return true;
//							&& mActivity.saveUserVCard(mActivity.avatorbytes, mActivity.username+"@pc2011040521xsg"));
//					return true;
				} catch (InterruptedException e) {

				}
				return false;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
				dismissLoadingDialog();
				if (result) {
				    Toast toast = Toast.makeText(RegisterActivity.this, String.format(
				    		getString(R.string.create_account_successfull_after), username), NOTIFICATION_DURATION);
				    	    toast.show();
				    	    
				    		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(RegisterActivity.this);
				    		SharedPreferences.Editor edit = settings.edit();
//				    		edit.putString(BeemApplication.ACCOUNT_USERNAME_KEY, mActivity.username+"@pc2011040521xsg");
				    		edit.putString(BeemApplication.ACCOUNT_USERNAME_KEY, username);
				    		edit.putString(BeemApplication.ACCOUNT_PASSWORD_KEY, password);
				    		edit.putString("uidStr", uidStr);
				    		edit.putString("uidStr"+username, uidStr);
				    		edit.commit();
					
					Intent i = new Intent(RegisterActivity.this, LoginanimActivity.class);//AccConfActivity    Login.class
				    i.putExtra("isConfig", 1);//0 false 1 true//注释掉，防止不经过登录过程直接进入主页后其他页面无法从上下文mXmppFacade.getXmppConnectionAdapter()获取getJID()等信息
				    i.putExtra("fromRegister", 1);
				    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				    RegisterActivity.this.startActivity(i);
				    
				    RegisterActivity.this.finish();
				}else{
					Toast toast = Toast.makeText(RegisterActivity.this, (String)errorMsg2.get(errorType), NOTIFICATION_DURATION);
				    	    toast.show();
				    RegisterActivity.this.finish();
				}
			}

		});
	}
	
	
	
	
	private String[] errorMsg3 = new String[]{"群聊创建成功.",
			"服务连接中1-1,请稍候再试.",
			"服务连接中1-2,请稍候再试.",
			"服务连接中1-3,请稍候再试.",
			"网络连接不可用,请检查你的网络设置.",
			"系统错误.群聊创建失败.",
			"用户已经加入了该群组，不能重复创建.",//0003
			"创建群组失败,hash校验失败"//0002
			};
	private int errorType3 = 5;
	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				if(errorType3!=5)
					showCustomToast(errorMsg3[errorType3]);
				else{
					showCustomToast("群聊创建成功!");
					startActivity(new Intent(RegisterActivity.this, ContactFrameActivity.class));//ContactListPullRefListActivity
					finish();	
				}
				break;

			case 1:
				
				progress.setText(msg.arg1+"%");//20150831 第三种方法
				bar.setProgress(msg.arg1);//20150831 第三种方法
				break;
			case 2:
				progress.setText("100%");//20150831 第三种方法
				bar.setProgress(100);//20150831 第三种方法
				
				creatingProgress.dismiss();
//				transformfilepath = 
				if(transformfilepath.lastIndexOf("/")!=-1)
					transformfilepath = XmppConnectionAdapter.downloadPrefix+"9999"+"/"+transformfilepath.substring(transformfilepath.lastIndexOf("/")+1);
				else
					transformfilepath = XmppConnectionAdapter.downloadPrefix+"9999"+"/"+transformfilepath;
				attributes.put("avatar", "1");//0默认未上传头像，1已上传头像
				break;
			case 3:
				progress.setText("上传失败!");
				creatingProgress.dismiss();
				break;
			case 4:
				initialProgressDialog();
				creatingProgress.show();
				break;
			default:
				if(errorType3!=5)
					showCustomToast(errorMsg3[errorType3]);
				break;
			}
		}

	};
	
	
	Uri uri = null;
	//利用requestCode区别开不同的返回结果
	//resultCode参数对应于子模块中setResut(int resultCode, Intent intent)函数中的resultCode值，用于区别不同的返回结果（如请求正常、请求异常等）
	//对应流程：
	//母模块startActivityForResult--触发子模块，根据不同执行结果设定resucode值，最后执行setResut并返回到木模块--母模块触发onActivityResult，根据requestcode参数区分不同子模块。
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==2 && resultCode==2 && data!=null){
        	String filepath = data.getStringExtra("filepath");
        	Toast.makeText(RegisterActivity.this, "filepath="+filepath, Toast.LENGTH_LONG).show();
			if(filepath.length() > 0){
//				sendFile(filepath);//P2P send file
				File file = new File(filepath);
				if (file.exists() && file.canRead()) {
					sendOfflineFile(filepath,"file");//send offline file via agent file server 
								    
				} else {
					Toast.makeText(RegisterActivity.this, "file not exists", Toast.LENGTH_LONG).show();
				}
			}
        }
        else if ( requestCode == GalleryHelper.GALLERY_REQUEST_CODE) {
            if ( resultCode == GalleryHelper.GALLERY_RESULT_SUCCESS ) {
                PhotoInfo photoInfo = data.getParcelableExtra(GalleryHelper.RESULT_DATA);
                List<PhotoInfo> photoInfoList = (List<PhotoInfo>) data.getSerializableExtra(GalleryHelper.RESULT_LIST_DATA);

                if ( photoInfo != null ) {
//                    ImageLoader.getInstance().displayImage("file:/" + photoInfo.getPhotoPath(), mIvResult);
                    uri = Uri.parse("file:/" + photoInfo.getPhotoPath());
                    Toast.makeText(this, "选择了照片路径:" + photoInfo.getPhotoPath(), Toast.LENGTH_SHORT).show();
                    sendOfflineFile(photoInfo.getPhotoPath(),"img");
                }

                if ( photoInfoList != null ) {
                    Toast.makeText(this, "选择了" + photoInfoList.size() + "张", Toast.LENGTH_SHORT).show();
                }
            }
        }
        else if ( requestCode == GalleryHelper.TAKE_REQUEST_CODE ) {
            if (resultCode == RESULT_OK && mTakePhotoUri != null) {
                final String path = mTakePhotoUri.getPath();
                final PhotoInfo info = new PhotoInfo();
                info.setPhotoPath(path);
//                updateGallery(path);

                final int degress = BitmapUtils.getDegress(path);
                if (degress != 0) {
                    new AsyncTask<Void, Void, Void>() {

                        @Override
                        protected void onPreExecute() {
                            super.onPreExecute();
                            toast("请稍等…");
                        }

                        @Override
                        protected Void doInBackground(Void... params) {
                            try {
                                Bitmap bitmap = rotateBitmap(path, degress);
                                saveRotateBitmap(bitmap, path);
                                bitmap.recycle();
                            } catch (Exception e) {
                                Logger.e(e);
                            }
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void voids) {
                            super.onPostExecute(voids);
//                            takeResult(info);
                            toPhotoCrop(info);
                        }
                    }.execute();
                } else {
//                    takeResult(info);
                	toPhotoCrop(info);
                }
            } else {
                toast("拍照失败");
            }
        } else if ( requestCode == GalleryHelper.CROP_REQUEST_CODE) {
            if ( resultCode == GalleryHelper.CROP_SUCCESS ) {
                PhotoInfo photoInfo = data.getParcelableExtra(GalleryHelper.RESULT_DATA);
                resultSingle(photoInfo);
            }
        } else if ( requestCode == GalleryHelper.GALLERY_RESULT_SUCCESS ) {
            PhotoInfo photoInfo = data.getParcelableExtra(GalleryHelper.RESULT_DATA);
            List<PhotoInfo> photoInfoList = (List<PhotoInfo>) data.getSerializableExtra(GalleryHelper.RESULT_LIST_DATA);

            if ( photoInfo != null ) {
//                ImageLoader.getInstance().displayImage("file:/" + photoInfo.getPhotoPath(), mIvResult);
                uri = Uri.parse("file:/" + photoInfo.getPhotoPath());
                Toast.makeText(this, "选择了照片路径:" + photoInfo.getPhotoPath(), Toast.LENGTH_SHORT).show();
                sendOfflineFile(photoInfo.getPhotoPath(),"img");
            }

            if ( photoInfoList != null ) {
                Toast.makeText(this, "选择了" + photoInfoList.size() + "张", Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    //recodeTime
    String transformfilepath = "";
    String transformfiletype = "";
    private void sendOfflineFile(String filepath,String type) {
		
    	transformfilepath = filepath;
    	transformfiletype = type;
    	
		try{
    		File file2 = new File(transformfilepath);
    		if(file2.exists()){
    			Bitmap bitmap = BitmapFactory.decodeFile(transformfilepath);
//    			setUserPhoto(bitmap);
    			mStepPhoto.setUserPhoto(bitmap);
    			upload(transformfilepath,"9999");
    			
    		}
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
    
    
    /**
     * 拍照
     */
    String mPhotoTargetFolder = null;
    Uri mTakePhotoUri = null;
    protected void takePhotoAction() {

        if (!DeviceUtils.existSDCard()) {
//            toast("没有SD卡不能拍照呢~");
        	Toast.makeText(this, "没有SD卡不能拍照呢~", Toast.LENGTH_SHORT).show();
            return;
        }

        File takePhotoFolder = null;
        if (cn.finalteam.toolsfinal.StringUtils.isEmpty(mPhotoTargetFolder)) {
            takePhotoFolder = new File(Environment.getExternalStorageDirectory(),
                    "/DCIM/" + GalleryHelper.TAKE_PHOTO_FOLDER);
        } else {
            takePhotoFolder = new File(mPhotoTargetFolder);
        }

        File toFile = new File(takePhotoFolder, "IMG" + DateUtils.format(new Date(), "yyyyMMddHHmmss") + ".jpg");
        boolean suc = cn.finalteam.toolsfinal.FileUtils.makeFolders(toFile);
        Logger.d("create folder=" + toFile.getAbsolutePath());
        if (suc) {
            mTakePhotoUri = Uri.fromFile(toFile);
            Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mTakePhotoUri);
            startActivityForResult(captureIntent, GalleryHelper.TAKE_REQUEST_CODE);
        }
    }
    protected int mScreenWidth = 720;
    protected int mScreenHeight = 1280;
    protected Bitmap rotateBitmap(String path, int degress) {
        try {
            Bitmap bitmap = BitmapUtils.compressBitmap(path, mScreenWidth / 4, mScreenHeight / 4);
            bitmap = BitmapUtils.rotateBitmap(bitmap, degress);
            return bitmap;
        } catch (Exception e) {
            Logger.e(e);
        }

        return null;
    }

    protected void saveRotateBitmap(Bitmap bitmap, String path) {
        //保存
        BitmapUtils.saveBitmap(bitmap, new File(path));
        //修改数据库
        ContentValues cv = new ContentValues();
        cv.put("orientation", 0);
        ContentResolver cr = getContentResolver();
        String where = new String(MediaStore.Images.Media.DATA + "='" + cn.finalteam.toolsfinal.StringUtils.sqliteEscape(path) +"'");
        cr.update(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, cv, where, null);
    }
    public void toast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
    protected void resultSingle(PhotoInfo photoInfo) {
//        Intent intent = getIntent();
//        if (intent == null) {
//            intent = new Intent();
//        }
//        intent.putExtra(GalleryHelper.RESULT_DATA, photoInfo);
////        setResult(GalleryHelper.GALLERY_RESULT_SUCCESS, intent);
////        finish();
//        startActivityForResult(intent, GalleryHelper.GALLERY_RESULT_SUCCESS);
    	
        if ( photoInfo != null ) {
//          ImageLoader.getInstance().displayImage("file:/" + photoInfo.getPhotoPath(), mIvResult);
          uri = Uri.parse("file:/" + photoInfo.getPhotoPath());
          Toast.makeText(this, "选择了照片路径:" + photoInfo.getPhotoPath(), Toast.LENGTH_SHORT).show();
          sendOfflineFile(photoInfo.getPhotoPath(),"img");
      }
    }
    /**
     * 执行裁剪
     */
    protected void toPhotoCrop(PhotoInfo info) {
        Intent intent = new Intent(this, PhotoCropActivity.class);
        intent.putExtra(PhotoCropActivity.PHOTO_INFO, info);
        startActivityForResult(intent, GalleryHelper.CROP_REQUEST_CODE);
    }
    
    
    public void upload(String mPicPath,String fromAccount){
    	try{
            final File file = new File(mPicPath);  
            
            if (file != null) {  
//                String request = UploadUtil.uploadFile(file, requestURL);  
//                String uploadHost="http://10.0.2.2:9090/plugins/offlinefiletransfer/offlinefiletransfer";  
            	String uploadHost = XmppConnectionAdapter.uploadHost.replace("OfflinefiletransferServlet", "UploadHeadServlet");
            	uploadHost = XmppConnectionAdapter.downloadPrefix + "/maps/Resource/uploadHead.jsp";
//                RequestParams params=new RequestParams();  
////                params.addBodyParameter("msg",imgtxt.getText().toString());   
//                params.addBodyParameter(picPath.replace("/", ""), file);   
//                uploadMethod(params,uploadHost);
////                uploadImage.setText(request);  
                RequestParams params = new RequestParams();
//                params.addHeader("name", "value");
//                params.addHeader(HttpUtils.HEADER_ACCEPT_ENCODING, HttpUtils.ENCODING_GZIP);
                params.addHeader("Accept-Encoding", "gzip");
//                params.addQueryStringParameter("name", "value");
//                params.addQueryStringParameter("fromAccount", fromAccount);//代表存储目录 原来在头像上传前不创建账户的话则存储到9999目录
                params.addQueryStringParameter("fromAccount", attributes.get("uid"));//代表存储目录，现在是上传头像前已经创建了账户，因此存储到对应的uid目录下
//                params.addQueryStringParameter("uid", uidStr);//上传照片时提交对应的用户uid=attributes.get("uid")
                SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
        	    String uid = settings.getString("uidStr", "");
        	    params.addQueryStringParameter("uidStr", uidStr);
        	    Log.e("※※※※※####20140806####※※※※※", "※※上传参数uidStr="+uidStr+";attributes.get(uid)="+attributes.get("uid")+";存储uid="+uid);
                params.addQueryStringParameter("sendType", "img");
                params.addQueryStringParameter("sendSize", "0");
                // 只包含字符串参数时默认使用BodyParamsEntity，
                // 类似于UrlEncodedFormEntity（"application/x-www-form-urlencoded"）。
//                params.addBodyParameter("fromAccount", fromAccount);
//                params.addBodyParameter("toAccount", toAccount);
//                params.addBodyParameter("sendType", "audio");
//                params.addBodyParameter("sendSize", (int) mRecord_Time+"");

                // 加入文件参数后默认使用MultipartEntity（"multipart/form-data"），
                // 如需"multipart/related"，xUtils中提供的MultipartEntity支持设置subType为"related"。
                // 使用params.setBodyEntity(httpEntity)可设置更多类型的HttpEntity（如：
                // MultipartEntity,BodyParamsEntity,FileUploadEntity,InputStreamUploadEntity,StringEntity）。
                // 例如发送json参数：params.setBodyEntity(new StringEntity(jsonStr,charset));
//                BodyParamsEntity bpe = new BodyParamsEntity();
//                bpe.addParameter("fromAccount", fromAccount);
//                bpe.addParameter("toAccount", toAccount);
//                bpe.addParameter("sendType", "audio");
//                bpe.addParameter("sendSize", (int) mRecord_Time+"");
//                params.setBodyEntity(bpe);
                params.addBodyParameter("file", file);
                Calendar now = Calendar.getInstance();//服务端按照这个年和月建立的文件存储子目录，有可能有时钟时间差，导致后台跨月的问题
                attributes.put("photo", "/userfiles/"+attributes.get("uid")+"/images/photo/"+now.get(Calendar.YEAR)+"/"+(now.get(Calendar.MONTH) + 1) +"/"+file.getName());
                //改了逻辑，后台接收到文件后直接更新数据库表sys_user对应的photo字段，本处attributes中的photo在后续接口中不上传到平台，只传photo=""
                uploadMethod(params,uploadHost);
                
            }  
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    
	private HttpUtils http;
	private HttpHandler handler;
	
    //上传照片start
    public  void uploadMethod(final RequestParams params,final String uploadHost) {  
    	http = new HttpUtils();
    	http.configCurrentHttpCacheExpiry(1000 * 10); // 设置缓存10秒，10秒内直接返回上次成功请求的结果。
    	
    	handler = http.send(HttpRequest.HttpMethod.POST, uploadHost, params,new RequestCallBack<String>() {  
                    @Override  
                    public void onStart() {  
//                      msgTextview.setText("conn...");  
                      mHandler.sendEmptyMessage(4);
                    }  
                    @Override  
                    public void onLoading(long total, long current,boolean isUploading) {  
//                        if (isUploading) {  
//                          msgTextview.setText("upload: " + current + "/"+ total);  
//                        } else {  
//                          msgTextview.setText("reply: " + current + "/"+ total);  
//                        }  
    					android.os.Message message = mHandler.obtainMessage();
//    					message.arg1 = (int) (current*100/total);
    					message.arg1 = 80;//gzip 后 total为0
    					message.what = 1;
    		//								message.sendToTarget();
    					mHandler.sendMessage(message);
                    }  
                    public void onSuccess(ResponseInfo<String> responseInfo) { 
                    	Log.e("※※※※※####20140806####※※※※※", "※※上传成功"+responseInfo.statusCode+";reply: " + responseInfo.result);
                    	//statuscode == 200
//                      msgTextview.setText("statuscode:"+responseInfo.statusCode+";reply: " + responseInfo.result); 
                    	
                    	mHandler.sendEmptyMessage(2);
                    }  
                    public void onFailure(HttpException error, String msg) {  
//                      msgTextview.setText(error.getExceptionCode() + ":" + msg);  
                    	Log.e("※※※※※####20140806####※※※※※", "※※上传失败"+error.getExceptionCode() + ":" + msg);
                    	mHandler.sendEmptyMessage(3);
                    }  
                });  
        
    } 
    //上传照片end
    
    private  Dialog creatingProgress = null;
	private ProgressBar bar;
	private TextView progress;
	
	public void initialProgressDialog(){
		//创建处理进度条
		creatingProgress= new Dialog(RegisterActivity.this,R.style.Dialog_loading_noDim);
		Window dialogWindow = creatingProgress.getWindow();
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		lp.width = (int) (getResources().getDisplayMetrics().density*240);
		lp.height = (int) (getResources().getDisplayMetrics().density*80);
		lp.gravity = Gravity.CENTER;
		dialogWindow.setAttributes(lp);
		creatingProgress.setCanceledOnTouchOutside(false);//禁用取消按钮
		creatingProgress.setContentView(R.layout.activity_recorder_progress);
		
		progress = (TextView) creatingProgress.findViewById(R.id.recorder_progress_progresstext);
		bar = (ProgressBar) creatingProgress.findViewById(R.id.recorder_progress_progressbar);
	}
}
